package db

import (
	"github.com/globalsign/mgo"
	"io/ioutil"
	"adai.design/homeserver/log"
	"encoding/json"
)

var dbSession *mgo.Session

type dbConfig struct {
	Url 		string		`json:"url"`
	Username 	string		`json:"username"`
	Password 	string		`json:"password"`
	DBName 		string		`json:"db_name"`
}

func getSession() (*mgo.Session, error) {
	if dbSession != nil {
		return dbSession.Copy(), nil
	}

	file := "conf/db.conf"
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		buf, err = ioutil.ReadFile("../" + file)
		if err != nil {
			log.Fatal("mongodb config file read err: %s", err)
		}
	}

	var conf dbConfig
	err = json.Unmarshal(buf, &conf)
	if err != nil {
		log.Fatal("mongodb config format err: %s", err)
	}

	dbSession, err = mgo.Dial(conf.Url)
	if err != nil {
		return nil, err
	}

	adminDB := dbSession.DB(conf.DBName)
	err = adminDB.Login(conf.Username, conf.Password)
	if err != nil {
		return nil, err
	}
	return dbSession.Copy(), nil
}











